/**
 * Created by xiangyufang on 2016/10/10.
 */
;(function($,window,document,undefined){
    /***全局变量初始化 start***/
    //表格
    var $table = $('#JQ_table').checkboxScroll();
    var DTTABLE;
    //任务Id
    var $taskId = $("#JQ_task_id").val();
    //是否易位
    var $isReverse = $('#JQ_reverse_text');
    //跟踪点列表
    var $point_list = $("#JQ_point_list");
    //跟踪点地图
    var $point_map = $("#JQ_point_map");
    //切换列表
    var $toggle_list = $("#JQ_toggle_list");
    //切换地图
    var $toggle_map = $("#JQ_toggle_map");
    //收缩表单
    var $map_pick = $('div.xyf-toggle-form-div');
    var $map_line = $('div.zy-pick-line');
    /***全局变量初始化 end***/


    /***表单条件初始化 start***/
    // 管道
    var $pipeline = $('#JQ_pipeline').select3();
    // 管段
    var $segment = $('#JQ_segment').select3({
        title:'管段'
    });
    // 起点位置
    var $begin = $('#JQ_begin').select3({
        title: '起点位置',
        server: true,
        mileType: 'float',
        pigType: 'pig',
        param: {'pipeLineId':$pipeline,'pipeSegmentId':$segment}
    });
    // 终点位置
    var $end = $('#JQ_end').select3({
        title:'终点位置',
        server: true,
        mileType: 'float',
        pigType: 'pig',
        param: {'pipeLineId':$pipeline,'pipeSegmentId':$segment,'beginSignId':$begin}
    });
    // 触发管道
    $pipeline.element.on('select',function(e,v){
        var id = v || $pipeline.val();
        if(id){
            $isReverse.val('0');
            // 管段
            DyyBase.ajax(cleanPipeApi.url_clean_segment(), {pipeLineId:id}, function(dataset){
                if(dataset.bool){
                    var json = DyyBase.getSelect(dataset.result);
                    $segment.add(json);
                }
            });
            //// 起点 & 终点
            DyyBase.ajax(cleanPipeApi.url_clean_beginEnd(), {pipeLineId:id}, function(dataset){
                var beginEndData = dataset.result;
                if(beginEndData.pipePosition !=null){
                    var begin = DyyBase.getNewPos(beginEndData,'begin',true);
                    var end = DyyBase.getNewPos(beginEndData,'end',true);
                    $begin.asset(begin);
                    $end.asset(end);
                }else{
                    $begin.add([]);
                    $end.add([]);
                    $("#JQ_begin_ball").text('场站阀室');
                    $("#JQ_end_ball").text('场站阀室');
                    $("#JQ_begin_ball").MSG({content:'所选管道无收发球筒，请重新选择!'});
                }

            },{async:false});
            DyyBase.search = true;
            drawBallData();
        }else{
            $segment.add([]);
            $begin.add([]);
            $end.add([]);
        }
    });
    // 触发管段
    $segment.element.on('select',function(e,v){
        var id = v || $segment.val();
        if(id){
            $isReverse.val('0');
            // 起点 & 终点
            DyyBase.ajax(cleanPipeApi.url_clean_beginSegmentEnd(), {pipeSegmentId:id}, function(dataset){
                var beginEndData = dataset.result;
                if(beginEndData.pipePosition !=null){
                    var begin = DyyBase.getNewPos(beginEndData,'begin',true);
                    var end = DyyBase.getNewPos(beginEndData,'end',true);
                    $begin.asset(begin);
                    $end.asset(end);
                }else{
                    $begin.add([]);
                    $end.add([]);
                    $("#JQ_begin_ball").text('场站阀室');
                    $("#JQ_end_ball").text('场站阀室');
                    $("#JQ_begin_ball").MSG({content:'所选管段无收发球筒，请重新选择!'});
                }
            },{async:false});
            DyyBase.search = true;
            drawBallData();
        }else{
            $begin.add([]);
            $end.add([]);
        }
    });
    //触发起点
    $begin.element.on('select',function(){
        $isReverse.val('0');
        DyyBase.search = true;
        drawBallData();
    });
    $end.element.on('select',function(){
        $isReverse.val('0');
        DyyBase.search = true;
        drawBallData();
    });
    //清管类型
    var $type = $('#JQ_type').select3({search:false});
    //清管工具
    var $tool_select = $('#JQ_tool_select').select3();
    /***表单条件初始化 end***/

     var filter = {
        //收发球点参数
        getBallData: function(){
            var filter = {};
            if(DyyBase.search === false){
                filter.taskId = '-1';
                filter.reverse = '-1';
                filter.lineId = '-1';
                filter.fromValId = '-1';
                filter.beginMile = '-1';
                filter.toValId = '-1';
                filter.endMile = '-1';
                return filter;
            }
            filter.taskId = $taskId;
            filter.reverse = function(){
                var v = $isReverse.val();
                if(v){
                    return v;
                }
                return '';
            }();
            filter.lineId = function(){
                var v = $pipeline.val('value');
                if(v){
                    return v;
                }
                return '';
            }();
            filter.fromValId = function(){
                var v = $begin.val('value');
                if(v){
                    return v;
                }
                return '';
            }();
            filter.beginMile = function(){
                var v = $begin.val('mile');
                if(v){
                    return v;
                }
                return '';
            }();
            filter.toValId = function(){
                var v = $end.val('value');
                if(v){
                    return v;
                }
                return '';
            }();
            filter.endMile = function(){
                var v = $end.val('mile');
                if(v){
                    return v;
                }
                return '';
            }();
            return filter;
        },
        //保存参数
        getBuildData: function(){
            var filter = {};
            filter.mode = true;
            filter.id = $taskId;
            //管道
            filter.pipeLineId = function(){
                var v = $pipeline.val();
                if(v){
                    return v;
                }else{
                    $('#JQ_pipeline').TIP({content:'管道名称不能为空！'});
                    filter.mode = false;
                }
            }();
            //起点
            filter.fromPipeValveroomId = function(){
                var v = $begin.val();
                if(v){
                    return v;
                }else{
                    $('#JQ_begin').TIP({content:'起点位置不能为空！'});
                    filter.mode = false;
                }
            }();
            //起点绝对距离
            filter.fromMileage = function(){
                var v = $begin.val('mile');
                if(v){
                    return v;
                }else if(v == 0){
                    return v
                }
                return '';
            }();
            //终点
            filter.toPipeValveroomId = function(){
                var v = $end.val();
                if(v){
                    return v;
                }else{
                    $('#JQ_end').TIP({content:'终点位置不能为空！'});
                    filter.mode = false;
                }
            }();
            //终点绝对距离
            filter.toMileage = function(){
                var v = $end.val('mile');
                if(v){
                    return v;
                }else if(v == 0){
                    return v
                }
                return '';
            }();
            //任务名称
            filter.taskName = function(){
                var v = $('#JQ_task').val();
                if(v){
                    return v;
                }else{
                    $('#JQ_task').TIP({content:'任务名称不能为空！'});
                    filter.mode = false;
                }
            }();
            //清管类型
            filter.pagType = function(){
                var v = $type.val();
                if(v){
                    return v;
                }else{
                    $('#JQ_type').TIP({content:'清管类型不能为空！'});
                    filter.mode = false;
                }
            }();
            //清管工具
            filter.pagTool = function(){
                var param = $('#JQ_Tool_type').val();
                if(param == "true"){
                    var v1 = $tool_select.val();
                    if(v1){
                        return v1;
                    }else{
                        $('#JQ_tool_select').TIP({content:'清管工具不能为空！'});
                        filter.mode = false;
                    }
                }else if(param == "false"){
                    var v = $('#JQ_tool_input').val();
                    if(v){
                        return v;
                    }else{
                        $('#JQ_tool_input').TIP({content:'清管工具不能为空！'});
                        filter.mode = false;
                    }
                }
            }();
            //清管时间
            filter.planPagDateTime = function(){
                var v = $('#JQ_Time').val();
                if(v){
                    return v;
                }else{
                    $('#JQ_Time').TIP({content:'计划清管时间不能为空！'});
                    filter.mode = false;
                }
            }();
            //备注
            filter.createRemark = function(){
                var v = $('#JQ_remark').val();
                if(v){
                    return v;
                }
                return '';
            }();
            //附件ID
            filter.attId = function(){
                var v = $("#JQ_file_name").attr('data-id');
                if(v){
                    return v;
                }
                return '';
            }();
            //是否易位
            filter.isAdverseCurrent = function(){
                var v = $('#JQ_reverse_text').val();
                if(v){
                    return v;
                }
                return '';
            }();
            //发球点Id
            filter.fromPigId = function(){
                var v = $('#JQ_begin_ball').attr("data-id");
                if(v){
                    return v;
                }
                return '';
            }();
            //收球点Id
            filter.toPigId = function(){
                var v = $('#JQ_end_ball').attr("data-id");
                if(v){
                    return v;
                }
                return '';
            }();
            return filter;
        },
        //表格复选框数据
        getCheckData: function(){
            var $checks = $table.find('i.zy-checkbox');
            ////数组储存id
            var arr = [];
            $checks.each(function () {
                var $this = $(this);
                if ($this.hasClass('active')) {
                    arr.push($this.attr('data-id'));
                }
            });
            return arr;
        },
        //地图跟踪点数据
        getCheckGISData: function(){
            var $checks = $table.find('i.zy-checkbox');
            //对象储存id
             var arr = [];
             $checks.each(function(){
                 var $this = $(this);
                 var obj = {name:'',mile:'',id:''};
                 if($this.hasClass('active')){
                     obj = {name:$this.attr('data-name'),mile:$this.attr('data-mile'),id:$this.attr('data-gis')};
                     arr.push(obj);
                 }
             });
             return arr;
        }
    };

    //获取收发球点
    function drawBallData(){
        $toggle_list.addClass('active');
        $toggle_map.removeClass("active");
        $point_list.show();
        $point_map.hide();
        removePoint();
        if(DTTABLE){
            DTTABLE.draw();
        }
        $('div.dataTables_scrollBody').css('overflow-x','hidden');
    }
    /***是新建还是编辑，需不需要拉取数据 start***/
    if($taskId){
        DyyBase.ajax(cleanPipeApi.url_clean_newTask_data(),{taskId:$taskId}, function(dataset){
            if(dataset.bool){
                var editData = dataset.result;
                $isReverse.val(editData.pigTask.isAdverseCurrent);
                //一般输入框默认值
                $("#JQ_task").val(editData.pigTask.taskName);
                $("#JQ_Time").val(editData.pigTask.planPagDateTime);
                $("#JQ_remark").val(editData.pigTask.createRemark);
                //导入附件
                var $taskAtt = editData.taskAtt;
                if($taskAtt){
                    $("#JQ_file_name").text($taskAtt.realName);
                    $("#JQ_file_name").attr('data-id',$taskAtt.id);
                    $("#JQ_file_name").attr('title',$taskAtt.realName);
                }

                //管道部分的默认值
                $pipeline.fit(editData.pigTask.pipeLineId);
                var pipeVal = editData.pigTask.pipeLineId;
                DyyBase.ajax(DyyBase.url_segment(), {pipeLineId:pipeVal}, function(dataset){
                    var json = DyyBase.getSelect(dataset);
                    $segment.add(json);
                },{async:false});
                // 起点 & 终点
                DyyBase.ajax(DyyBase.url_pipe_pos(), {pipeLineId:pipeVal}, function(dataset){
                    var begin = DyyBase.getPos(dataset,'begin',true);
                    var end = DyyBase.getPos(dataset,'end',true);
                    $begin.add(begin).fit(editData.pigTask.fromPipeValveroomId);
                    $end.add(end).fit(editData.pigTask.toPipeValveroomId);
                },{async:false});
                DyyBase.search = true;
                drawBallData();

                //清管类型和清管工具默认值
                var typeId = editData.pigTask.pagType;
                var toolId = editData.pigTask.pagTool;
                var isTool = editData.pigTask.isDropDown;
                $("#JQ_Tool_type").val(isTool);
                loadTypeTool(typeId,toolId,isTool);
            }
        },{async:false});
    }else{
        loadTypeTool();
    }

    //清管数据和清管工具请求
    function loadTypeTool(typeId,toolId,isTool){
        var $tool_i= $("#JQ_toolI");
        var $tool_s= $("#JQ_toolS");
        DyyBase.ajax(cleanPipeApi.url_history_cleanType(),{}, function(dataset){
            var json = DyyBase.getSelect(dataset);
            if(typeId){
                $type.add(json).fit(typeId);
            }else{
                $type.add(json);
            }
        },{async:false});
        if(isTool == true){
            $tool_i.hide();
            $tool_s.show();
            var $type_name = $type.val('text');
            DyyBase.ajax(cleanPipeApi.url_history_cleanTool(),{pagTypeName:$type_name}, function(dataset){
                if(dataset.bool){
                    var json = dataset.result;
                    var data = DyyBase.getSelect(json.cleanTool);
                    $tool_select.add(data).fit(toolId);
                }
            },{async:false})
        }else if(isTool == false){
            $tool_s.hide();
            $tool_i.show();
            $("#JQ_tool_input").val(toolId);
        }else{
        }
        $type.element.on('select',function(){
            var Name = $type.val('text');
            DyyBase.ajax(cleanPipeApi.url_history_cleanTool(),{pagTypeName:Name}, function(dataset){
                if(dataset.bool){
                    var json = dataset.result;
                    $("#JQ_Tool_type").val(json.isDropDown);
                    if(json.isDropDown == true){
                        $tool_i.hide();
                        $tool_s.show();
                        var data = DyyBase.getSelect(json.cleanTool);
                        $tool_select.add(data);
                    }else if(json.isDropDown == false){
                        $tool_s.hide();
                        $tool_i.show();
                    }
                }
            },{async:false});
        });
    }
    /***是新建还是编辑，需不需要拉取数据 end***/

    //切换收发球点
    $("#JQ_exchange_ball").click(function(){
        var param = $isReverse.val();
        if(param == '0'){
            $isReverse.val('1');
        }else if(param == '1'){
            $isReverse.val('0');
        }
        DyyBase.search = true;
        drawBallData();
    });

    //**表格数据**
    function pointTable(){
        DTTABLE = $table.DataTable({
            'language': {
                'zeroRecords': DyyBase.table_empty()
            },
            'info': false,
            'paging': false,
            'scrollY': 360,
            'autoWidth': false,
            'order': [],
            'serverSide': true,
            'pageLength': 1000,
            'ordering': false,
            'processing': false,
            'searching': false,
            'lengthChange': false,
            'ajax': function(data,callback){
                var param = filter.getBallData();
                DyyBase.ajax(cleanPipeApi.url_clean_newTask_ball(),param, function(dataset){
                    if(dataset.bool){
                        var $begin_ball = $("#JQ_begin_ball");
                        var $end_ball =$("#JQ_end_ball");
                        var $scroll_begin_ball = $("#JQ_scroll_begin_ball");
                        var $scroll_end_ball = $("#JQ_scroll_end_ball");
                        var ballData = dataset.result;
                        if(ballData.fromPig){
                            $begin_ball.text(ballData.fromPig.PIPEVALNAME);
                            $begin_ball.attr('data-id',ballData.fromPig.ID);
                            $scroll_begin_ball.text(ballData.fromPig.PIPEVALNAME);
                            $scroll_begin_ball.attr('data-id',ballData.fromPig.GISID);
                            $("#JQ_scroll_begin_mile").text(ballData.fromPig.MILEAGE)
                        }
                        if(ballData.toPig){
                            $end_ball.text(ballData.toPig.PIPEVALNAME);
                            $end_ball.attr('data-id',ballData.toPig.ID);
                            $scroll_end_ball.text(ballData.toPig.PIPEVALNAME);
                            $scroll_end_ball.attr('data-id',ballData.toPig.GISID);
                            $("#JQ_scroll_end_mile").text(ballData.toPig.MILEAGE)
                        }
                        var returnData = {};
                        returnData.data = DyyBase.clearNull(ballData.markPoint);
                        callback(returnData);

                        $("#JQ_check_all").attr('data-chk', 'false').removeClass('active');
                    }
                });
            },
            'drawCallback': function () {

            },
            'columns': [
                {
                    data: 'id',
                    render: function (data,type,row) {
                        if(row.isPassRecord == "Y"){
                            return '<i class="zy-checkbox active" data-id="' + data + '" data-name="' + row.locationDescription + '" data-mile="' + row.mileage  + '" data-gis="' + row.gisId + '" title="选中"></i>';
                        }else if(row.isPassRecord == "N"){
                            return '<i class="zy-checkbox" data-id="' + data + '" data-name="' + row.locationDescription + '" data-mile="' + row.mileage  + '" data-gis="' + row.gisId +  '" title="选中"></i>';
                        }else{
                            return '<i class="zy-checkbox" data-id="' + data + '" data-name="' + row.locationDescription + '" data-mile="' + row.mileage  + '" data-gis="' + row.gisId +  '" title="选中"></i>';
                        }

                    }
                },
                {
                    data: 'pointType',
                    render: function (data) {
                        return '<span title="' + data + '">' + data + '</span>';
                    }
                },
                {
                    data: 'locationDescription',
                    render: function (data) {
                        return '<span title="' + data + '">' + data + '</span>';s
                    }
                },
                {
                    data: 'mileage',
                    render: function (data) {
                        return '<span title="' + data + '">' + data + '</span>';
                    }
                },
                {
                    data: 'reference',
                    render: function (data) {
                        return '<span title="' + data + '">' + data + '</span>';
                    }
                },
                {
                    data: 'referenceDistance',
                    render: function (data) {
                        return '<span title="' + data + '">' + data + '</span>';
                    }
                },
                {
                    data: 'remark',
                    render: function (data) {
                        return '<span title="' + data + '">' + data + '</span>';
                    }
                },
                {
                    data: 'gisId',
                    render: function (data,type,row) {
                        return '<i data-a="' + data + '" data-id="' + row.id + '" class="xyf-see-map-icon" title="查看地图"></i>';
                    }
                }
            ]
        });
    }
    pointTable();

    //导入文件
    $("#JQ_import").click(function(){
        var $this = $(this);
        $this.UPW({
            businessId: $taskId,
            fileType: 'piggingTaskAtt',
            closeBtnAct: function(callback){
                callback();
                var setData = $.parseJSON($this.data('info').response);
                if(setData.bool){
                    var fileData = setData.result;
                    $("#JQ_file_name").text(fileData.fileName);
                    $("#JQ_file_name").attr('data-id',fileData.id);
                    $("#JQ_file_name").attr('title',fileData.fileName);
                }
            }
        });
    });

    //保存
    $('#JQ_save').click(function(){
        var param = filter.getBuildData();
        if(param.mode){
            var points = filter.getCheckData();
            if(points.length>0){
                param.points = points;
                DyyBase.ajax(cleanPipeApi.url_clean_newTask_save(), DyyBase.convertToArr(param), function(dataset){
                    if(dataset.bool){
                        $table.MSG({
                            type: 'success',
                            height: 300,
                            content: '保存成功',
                            yesBtnTxt: '确认',
                            yesBtnAct: function(){
                                var url = cleanPipeApi.url_clean_newTask_Manege();
                                window.location.href = url;
                            }
                        });
                    }else{
                        $table.MSG({ type: 'error',
                            height: 300,
                            content: dataset.message
                        });
                    }
                });

            }else {
                $table.MSG({
                    content:"请至少选择一个跟踪点！"
                })
            }
        }
    });


    //切换到列表页
    $toggle_list.click(function(){
        $map_pick.removeClass('active');
        $map_line.slideDown();
        $(this).addClass('active');
        $toggle_map.removeClass("active");
        $point_list.show();
        $point_map.hide();
        removePoint();
    });

    //切换到地图部分，加载GIS地图和跟踪点
    $toggle_map.click(function(){
        $map_pick.addClass('active');
        $map_line.slideUp();
        var url = 'baseMapPigTaskManage.jsp';
        $(this).addClass('active');
        $toggle_list.removeClass("active");
        $point_list.hide();
        $point_map.show();
        loadPoint();
        loadGIS('',url);

    });

    //点击图标跳转到地图页
    $table.on("click","i.xyf-see-map-icon",function(event){
        $map_pick.addClass('active');
        $map_line.slideUp();
        var $this = $(this);
        var id = $this.attr("data-a");
        var gisUrl = 'baseMapPigTaskManageLoc.jsp';
        $toggle_map.addClass('active');
        $toggle_list.removeClass("active");
        $point_list.hide();
        $point_map.show();
        loadPoint();
        loadGIS(id,gisUrl);

        var arr = filter.getCheckData();
        var sort_id = $this.attr("data-id");
        var index = arr.indexOf(sort_id);
        if(arr.length > 3){
            var scroll_left = 180 + 220*index;
            $("#JQ_xyf-slide").scrollLeft(scroll_left);
        }
        event.stopPropagation();
    });

    //点击地图页的发球点在地图上显示发球点
    $("#JQ_begin_point").click(function(){
        var id = $("#JQ_scroll_begin_ball").attr('data-id');
        document.getElementById("dyMap").contentWindow.locateTarget(id,'piggingstructure');
    });
    //点击地图页的发球点在地图上显示收球点
    $("#JQ_end_point").click(function(){
        var id = $("#JQ_scroll_end_ball").attr('data-id');
        document.getElementById("dyMap").contentWindow.locateTarget(id,'piggingstructure');
    });

    //点击跟踪点数据
    $("#JQ_slide_content").delegate("div.xyf-link-point",'click',function(){
        var $this = $(this);
        var Id = $this.attr("id");
        document.getElementById("dyMap").contentWindow.locateTarget(Id,'mark');
    });

    //删除已有的跟踪点
    function removePoint(){
        $("div").remove('.xyf-link-point');
    }

    $("#mapDiv").find('iframe').css({
        'scrolling':0,
        'frameborder':0,
        'border':0,
        'padding':0,
        'margin': 0,
        'width':'100%',
        'height':'100%'
    });

    //加载跟踪点
    function loadPoint(){
        var $begin_point = $("#JQ_begin_point");
        var data = filter.getCheckGISData();
        var visibleData = data.reverse();
        var len = visibleData.length;
        var slide_w = 220*len + 160*2;
        $("#JQ_slide_content").css("width",slide_w);
        for(var i=0;i<len;i++){
            var content ='';
            content = '<div id="' + visibleData[i].id + '"  class="xyf-link-point">';
            content += '<div class="xyf-link_point-top"><div class="link_point-top-img"></div><div class="link_point-top-line"></div><div class="clear"></div></div>';
            content += '<p class="link-point-number">'+ visibleData[i].name + '</p>';
            content += '<p>绝对距离(m)：' + visibleData[i].mile + '</p>';
            content +='</div>';
            var $link_point = $(content);
            $begin_point.after($link_point);
        }
    }

    //加载gis地图
    function loadGIS(id,url){
        var gisResourcePath = $("#gisResourcePath").val();
        var param = filter.getBallData();
        if(id){
            param.activePointGisId = id;
        }
        var idArr = filter.getCheckData();
        param.pointArry = idArr;
        DyyBase.ajax(cleanPipeApi.url_clean_newTask_gis(), DyyBase.convertToArr(param), function (dataset) {
            loadGis($("#mapDiv"), gisResourcePath + url,dataset.result);
        });
    }

})(jQuery,window,document);